package com.qining618.cms.ucenter.service.impl;

import com.qining618.cms.ucenter.domain.Role;
import com.qining618.cms.ucenter.domain.RoleMenu;
import com.qining618.cms.ucenter.mapper.RoleMapper;
import com.qining618.cms.ucenter.service.RoleMenuService;
import com.qining618.cms.ucenter.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qining618.common.exception.BusinessException;
import com.qining618.common.result.ErrorCode;
import com.qining618.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author qining
 * @date 2019-09-16
 */
@Transactional(readOnly = true, rollbackFor = Exception.class)
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMenuService roleMenuService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Role add(String name) {
        Role role = new Role();
        role.setName(name);
        int opNum = this.baseMapper.insert(role);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }
        return role;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Role edit(Long id, String name) {
        // 检验菜单是否存在
        Role role = this.baseMapper.selectById(id);
        if (role == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "角色不存在");
        }
        role.setName(name);
        int opNum = this.baseMapper.updateById(role);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }
        return role;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setMenuIds(Long id, List<Long> menuIds) {
        Role role = this.baseMapper.selectById(id);
        if (role == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "角色不存在");
        }
        role.setMenuIds(StringUtils.join(menuIds, ","));
        this.baseMapper.updateById(role);

        // 删除角色菜单信息
        this.roleMenuService.deleteByRoleId(id);
        for (Long menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(id).setMenuId(menuId);
            boolean result = this.roleMenuService.save(roleMenu);
            if (!result) {
                throw new BusinessException(ErrorCode.DB_ERROR);
            }
        }
    }

    @Override
    public boolean existById(Long id) {
        return this.baseMapper.existById(id);
    }
}
